package com.ruoyi.system.controller;
import java.util.Map;
import java.util.HashMap;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;
import javax.servlet.http.HttpServletResponse;
import com.ruoyi.common.core.web.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.system.domain.SysVideo;
import com.ruoyi.system.service.ISysVideoService;

@RestController
@RequestMapping("/file")
public class FileController extends BaseController {

    @Value("${ruoyi.profile}")
    private String uploadPath;

    @Autowired
    private ISysVideoService sysVideoService;

    /**
     * 上传视频文件
     */
    @PostMapping("/uploadVideo")
    public AjaxResult uploadVideo(@RequestParam("file") MultipartFile file) {
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                return AjaxResult.error("上传文件不能为空");
            }

            // 检查文件大小，限制为500MB
            long maxSize = 500 * 1024 * 1024;
            if (file.getSize() > maxSize) {
                return AjaxResult.error("文件大小不能超过500MB");
            }

            // 检查文件类型
            String contentType = file.getContentType();
            if (!contentType.startsWith("video/")) {
                return AjaxResult.error("只能上传视频文件");
            }

            // 创建上传目录
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFilename = UUID.randomUUID().toString() + fileExtension;

            // 保存文件
            Path path = Paths.get(uploadPath + newFilename);
            Files.write(path, file.getBytes());

            // 保存视频信息到数据库
            SysVideo video = new SysVideo();
            video.setVideoName(originalFilename);
            video.setVideoPath(newFilename);
            // 这里可以添加获取视频时长的逻辑
            sysVideoService.insertVideo(video);

            return AjaxResult.success("文件上传成功", newFilename);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("文件上传失败");
        }
    }

    /**
     * 下载视频文件
     */
    @GetMapping("/downloadVideo")
    public void downloadVideo(@RequestParam String filename, HttpServletResponse response) {
        try {
            Path path = Paths.get(uploadPath + filename);
            if (Files.exists(path)) {
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
                Files.copy(path, response.getOutputStream());
                response.getOutputStream().flush();
            } else {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 流式传输视频
     */
    @GetMapping("/streamVideo")
    public void streamVideo(@RequestParam String filename, HttpServletResponse response) {
        try {
            Path path = Paths.get(uploadPath + filename);
            if (Files.exists(path)) {
                response.setContentType("video/mp4");
                Files.copy(path, response.getOutputStream());
                response.getOutputStream().flush();
            } else {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取文件静态资源URL
     */
    @GetMapping("/getUrl")
    public AjaxResult getFileUrl(@RequestParam Long videoId) {
        // 1. 从数据库查询视频记录
        SysVideo video = sysVideoService.selectVideoById(videoId);
        if (video == null) {
            return error("视频不存在");
        }

        // 2. 检查物理文件是否存在
        Path path = Paths.get(uploadPath + File.separator + video.getVideoPath());
        if (!Files.exists(path)) {
            return error("视频文件不存在");
        }

        // 3. 返回结果
        return success(new HashMap<String, String>() {{
            put("url", getStaticResourceUrl(video.getVideoPath()));
        }});
    }

    private String getStaticResourceUrl(String filename) {
        return String.format("http://192.168.1.103:%s/system/videos/%s", 8080, filename);
    }
}